package com.dy.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: dy
 * @Date: 2022/4/16 - 04 - 16 - 17:44
 * @Description: com.dy.config
 * @version: 1.0
 */
@Configuration
public class RabbitMqConfig {
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Bean//配置rabbitmq模板
    public RabbitTemplate rabbitTemplate(){
        return new RabbitTemplate(cachingConnectionFactory);
    }

    @Bean//关联死信交换机的正常队列
    public Queue deadOrderQueue(){
        //关联死信交换机
        Map<String, Object> args = new HashMap<>(3);
        // x-dead-letter-exchange  这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange","dyDeadExchange");
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key","dead.order");
        // x-message-ttl  声明队列的TTL, 设置消息为死信时间:ms毫秒单位
        args.put("x-message-ttl",5000);
        //返回的是一个关联了死信交换机的队列
        return QueueBuilder.durable("dyOrderQueue").withArguments(args).build();
    }

    @Bean//死信队列
    public Queue deadQueue(){
        return new Queue("dyDeadQueue");
    }

    @Bean//死信交换机
    public DirectExchange deadExchange(){
        return new DirectExchange("dyDeadExchange");
    }

    @Bean//绑定
    public Binding deadBind(Queue deadQueue,DirectExchange deadExchange){
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("dead.order");
    }

    @Bean//配置交换机
    public DirectExchange directExchange(){
        return new DirectExchange("dyDirectExchange");
    }

    @Bean//消息队列绑定交换机
    public Binding binding(Queue deadOrderQueue, DirectExchange directExchange){
        return BindingBuilder.bind(deadOrderQueue).to(directExchange).with("order.queue");
    }

    @Bean //抢票队列
    public Queue queueShakedown(){
        return new Queue("shakedownQueue");
    }

    @Bean //抢票交换机
    public DirectExchange exchangeShakedown(){
        return new DirectExchange("shakedownExchange");
    }

    @Bean //绑定
    public Binding bing(Queue queueShakedown,DirectExchange exchangeShakedown){
        return BindingBuilder.bind(queueShakedown).to(exchangeShakedown).with("shakedown.queue");
    }
}
